<template>
  <view class="container">
    <view class="upload-section">
      <text class="section-title">图片上传</text>
      
      <!-- 选择图片按钮 -->
      <button class="primary-btn" @click="chooseImage">选择图片</button>
      
      <!-- 图片预览区域 -->
      <view class="image-preview" v-if="tempImagePath">
        <image :src="tempImagePath" mode="aspectFit" class="preview-image"></image>
        <button class="delete-btn" @click="deleteImage">删除</button>
      </view>
      
      <!-- 上传进度 -->
      <view class="upload-progress" v-if="uploadProgress > 0 && uploadProgress < 100">
        <text>上传进度: {{ uploadProgress }}%</text>
        <progress :percent="uploadProgress" stroke-width="4" activeColor="#07c160" backgroundColor="#eeeeee"></progress>
      </view>
      
      <!-- 上传按钮 -->
      <button class="primary-btn" @click="uploadImage" :disabled="!tempImagePath || uploadLoading">
        {{ uploadLoading ? '上传中...' : '上传图片' }}
      </button>
      
      <!-- 上传结果 -->
      <view class="upload-result" v-if="uploadResult">
        <text class="section-title">上传结果</text>
        <view class="result-item" v-for="(value, key) in uploadResult" :key="key">
          <text class="item-key">{{ key }}:</text>
          <text class="item-value">{{ value }}</text>
        </view>
      </view>
      
      <!-- 错误提示 -->
      <view class="error" v-if="uploadError">
        <text>{{ uploadError }}</text>
        <button @click="retryUpload">重试</button>
      </view>
      
      <!-- 历史上传记录 -->
      <view class="history-section" v-if="uploadHistory.length > 0">
        <text class="section-title">上传历史</text>
        <view class="history-list">
          <view class="history-item" v-for="(item, index) in uploadHistory" :key="index">
            <image :src="item.url" mode="aspectFit" class="history-image"></image>
            <text class="history-info">{{ item.filename }}</text>
            <text class="history-time">{{ formatDate(item.uploadTime) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '../../store/user'
import { uploadFile } from '../../utils/request'

const userStore = useUserStore()

// 响应式数据
const tempImagePath = ref('') // 临时图片路径
const uploadProgress = ref(0) // 上传进度
const uploadLoading = ref(false) // 上传加载状态
const uploadError = ref('') // 上传错误信息
const uploadResult = ref(null) // 上传结果
const uploadHistory = ref([]) // 上传历史记录

// 页面加载时检查登录状态
onLoad(() => {
  if (!userStore.isLogin) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/login'
      })
    }, 1500)
  }
  
  // 加载上传历史
  loadUploadHistory()
})

// 选择图片
const chooseImage = async () => {
  try {
    const res = await uni.chooseImage({
      count: 1, // 只能选择一张图片
      sizeType: ['compressed'], // 压缩图片
      sourceType: ['album', 'camera'], // 可从相册和相机选择
    })
    
    if (res.tempFilePaths && res.tempFilePaths.length > 0) {
      // 清除之前的错误信息
      uploadError.value = ''
      
      // 设置选择的图片路径
      tempImagePath.value = res.tempFilePaths[0]
      
      // 清除之前的上传结果
      uploadResult.value = null
    }
  } catch (error) {
    console.error('选择图片失败:', error)
    // 用户取消选择时不显示错误提示
    if (!error.errMsg.includes('cancel')) {
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  }
}

// 删除已选择的图片
const deleteImage = () => {
  tempImagePath.value = ''
  uploadResult.value = null
  uploadError.value = ''
}

// 上传图片
const uploadImage = async () => {
  if (!tempImagePath.value) {
    uni.showToast({
      title: '请先选择图片',
      icon: 'none'
    })
    return
  }
  
  uploadLoading.value = true
  uploadError.value = ''
  uploadProgress.value = 0
  
  try {
    // 调用uploadFile方法上传图片
    const res = await uploadFile('/upload/image', tempImagePath.value, {
      name: 'image', // 文件对应的key
      formData: {
        type: 'avatar', // 其他表单参数
        desc: '用户上传的图片'
      },
      loading: false, // 不使用默认的加载提示，自己控制
      onProgressUpdate: (res) => {
        // 更新上传进度
        uploadProgress.value = res.progress
      }
    })
    
    if (res.success) {
      // 上传成功，保存结果
      uploadResult.value = res.data || {}
      
      // 添加到上传历史
      addToHistory({
        url: res.data.url || '',
        filename: res.data.filename || '上传图片',
        uploadTime: new Date().getTime()
      })
      
      // 显示成功提示
      uni.showToast({
        title: '图片上传成功',
        icon: 'success'
      })
    } else {
      uploadError.value = res.msg || '图片上传失败'
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    uploadError.value = error.message || '网络异常，请稍后重试'
  } finally {
    uploadLoading.value = false
    // 上传完成或失败后，重置进度条
    setTimeout(() => {
      uploadProgress.value = 0
    }, 1500)
  }
}

// 重试上传
const retryUpload = () => {
  if (tempImagePath.value) {
    uploadImage()
  }
}

// 添加到上传历史
const addToHistory = (item) => {
  uploadHistory.value.unshift(item) // 添加到数组开头
  
  // 限制历史记录数量
  if (uploadHistory.value.length > 10) {
    uploadHistory.value = uploadHistory.value.slice(0, 10)
  }
  
  // 保存到本地存储
  uni.setStorageSync('uploadHistory', uploadHistory.value)
}

// 加载上传历史
const loadUploadHistory = () => {
  const history = uni.getStorageSync('uploadHistory')
  if (history && Array.isArray(history)) {
    uploadHistory.value = history
  }
}

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.upload-section {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 20rpx;
  color: #333333;
}

.primary-btn {
  background-color: #07c160;
  color: #ffffff;
  margin-bottom: 30rpx;
}

.primary-btn:disabled {
  background-color: #cccccc;
  color: #ffffff;
}

.image-preview {
  margin-bottom: 30rpx;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 400rpx;
  border-radius: 10rpx;
  border: 1rpx solid #eeeeee;
}

.delete-btn {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  background-color: rgba(255, 77, 79, 0.9);
  color: #ffffff;
  font-size: 24rpx;
  padding: 0 20rpx;
  height: 50rpx;
  line-height: 50rpx;
}

.upload-progress {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 10rpx;
}

.upload-progress text {
  font-size: 28rpx;
  color: #333333;
  display: block;
  margin-bottom: 10rpx;
}

.upload-result {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 10rpx;
}

.result-item {
  display: flex;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #eeeeee;
}

.result-item:last-child {
  border-bottom: none;
}

.item-key {
  font-size: 28rpx;
  color: #666666;
  margin-right: 10rpx;
}

.item-value {
  font-size: 28rpx;
  color: #333333;
  flex: 1;
}

.error {
  text-align: center;
  padding: 40rpx 0;
  color: #ff4d4f;
  background-color: #fff2f0;
  border-radius: 10rpx;
  margin-bottom: 30rpx;
}

.error button {
  margin-top: 20rpx;
  font-size: 28rpx;
  background-color: #07c160;
  color: #ffffff;
}

.history-section {
  margin-top: 30rpx;
  padding-top: 30rpx;
  border-top: 1rpx solid #eeeeee;
}

.history-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.history-item {
  width: calc(33.33% - 13rpx);
  text-align: center;
}

.history-image {
  width: 100%;
  height: 150rpx;
  border-radius: 10rpx;
  margin-bottom: 10rpx;
}

.history-info {
  font-size: 24rpx;
  color: #333333;
  display: block;
  margin-bottom: 5rpx;
}

.history-time {
  font-size: 20rpx;
  color: #999999;
  display: block;
}
</style>